package cn.linkpower.aop;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class TokenAspcetj {
	
	/**
	 * 定义注解
	 * @author 765199214
	 *
	 */
	@Retention(RetentionPolicy.RUNTIME)
	@Target({ElementType.METHOD,ElementType.TYPE}) //用于类和方法
	public @interface AccessResource {
		
	}
	
	/**
	 * 针对“自定义注解”，定义切点
	 */
	@Pointcut("@annotation(cn.linkpower.aop.TokenAspcetj.AccessResource)")
	public void resource() {
		
	}
	
	/**
	 * 使用了注解的接口，实现aop
	 * @param pjp
	 * @return
	 * @throws Throwable
	 */
	@Around("resource()") //ProceedingJoinPoint 必须使用 @Around
	public Object check(ProceedingJoinPoint pjp) throws Throwable{
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = requestAttributes.getRequest();
		String token = request.getParameter("token");
		if(token == null || "".equals(token)) {
			return "token无效";
		}
		return pjp.proceed();
	}
	
}
